/* Copyright (c) 2023-2023, LiWangQian<liwangqian@huawei.com> All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this list of
 *    conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice, this list
 *    of conditions and the following disclaimer in the documentation and/or other materials
 *    provided with the distribution.
 *
 * 3. Neither the name of the copyright holder nor the names of its contributors may be used
 *    to endorse or promote products derived from this software without specific prior written
 *    permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
#include "libevent/broker.h"
#include "libevent/status.h"
#include "libevent/base/listener.h"

namespace libev {

broker::~broker()
{
    shutdown();
}

broker::broker(const stl::string &name)
    : name_{name}
{
}

status broker::setup(const config &cfg)
{
    // empty
    return LIBEV_STATUS_OK;
}

void broker::shutdown() noexcept
{
    std::shared_lock<decltype(mutex_)> lock{mutex_};
    for (auto &[_, t] : topics_) {
        t->shutdown();
    }
}

const stl::string &broker::name() const noexcept
{
    return name_;
}

status broker::new_topic(const stl::string &topic_name,
    const base::topic::config &cfg)
{
    auto topic = stl::make_shared<base::topic>(topic_name);
    if (topic == nullptr) {
        return LIBEV_STATUS_OUT_MEMORY;
    }

    auto res = topic->setup(cfg);
    if (res != LIBEV_STATUS_OK) {
        return res;
    }

    bool inserted = false;
    {
        std::unique_lock<decltype(mutex_)> lock{mutex_};
        inserted = topics_.try_emplace(topic_name, std::move(topic)).second;
    }

    if (!inserted) {
        return LIBEV_STATUS_EXISTED;
    }

    emit_broker_event(evt_new_topic, topic_name);
    return LIBEV_STATUS_OK;
}

status broker::del_topic(const stl::string &topic_name)
{
    {
        std::unique_lock<decltype(mutex_)> lock{mutex_};
        auto iter = topics_.find(topic_name);
        if (iter == std::end(topics_)) {
            return LIBEV_STATUS_NOT_EXIST;
        }
        (void)topics_.erase(iter);
    }

    emit_broker_event(evt_del_topic, topic_name);
    return LIBEV_STATUS_OK;
}

bool broker::has_topic(const stl::string &name) const noexcept
{
    std::shared_lock<decltype(mutex_)> lock{mutex_};
    return topics_.find(name) != std::end(topics_);
}

status broker::sub_from_topic(const stl::string &topic,
    stl::unique_ptr<base::listener> listener)
{
    if (listener == nullptr) {
        return LIBEV_STATUS_NULL_PTR;
    }
    auto t = get_topic(topic);
    return t ? t->sub(topic, std::move(listener)) : LIBEV_STATUS_NOT_EXIST;
}

status broker::unsub_from_topic(const stl::string &topic,
    const stl::string &listener)
{
    auto t = get_topic(topic);
    return t ? t->unsub(listener) : LIBEV_STATUS_NOT_EXIST;
}

status broker::pub_to_topic(const stl::string &topic,
    stl::shared_ptr<base::event> evt, const schedule_policy &policy)
{
    if (evt == nullptr) {
        return LIBEV_STATUS_NULL_PTR;
    }

    auto t = get_topic(topic);
    return t ? t->pub(std::move(evt), policy) : LIBEV_STATUS_NOT_EXIST;
}

status broker::pub_to_topic_async(const stl::string &topic,
    stl::shared_ptr<base::event> evt, const schedule_policy &policy)
{
    if (evt == nullptr) {
        return LIBEV_STATUS_NULL_PTR;
    }

    auto t = get_topic(topic);
    return t ? t->pub_async(std::move(evt), policy) : LIBEV_STATUS_NOT_EXIST;
}

stl::forward_list<stl::string> broker::list_topics() const
{
    stl::forward_list<stl::string> list;
    {
        std::shared_lock<decltype(mutex_)> lock{mutex_};
        for (auto &[name, _] : topics_) {
            list.push_front(name);
        }
    }
    return list;
}

size_t broker::topics_count() const noexcept
{
    std::shared_lock<decltype(mutex_)> lock{mutex_};
    return topics_.size();
}

stl::shared_ptr<base::topic> broker::get_topic(const stl::string &name) const
{
    std::shared_lock<decltype(mutex_)> lock{mutex_};
    auto iter = topics_.find(name);
    if (iter == topics_.end()) {
        return nullptr;
    }
    return iter->second;
}

void broker::emit_broker_event(event_type etype, const stl::string &topic_name)
{
    schedule_policy sch{ .mode = access_mode::write, .pri = priority::normal };
    (void)pub_to_topic_async(broker_topic,
        stl::make_shared<broker_event>(etype, name_, topic_name), sch);
}

} // namespace libev

